#include "doublelist.h"

/*
struct doublelist
{	//数据域
	char name[20];
	float price;
	int num;
	char picpath[20];
	
	struct doublelist *next; //指针域
	struct doublelist *prev;
};
*/

//双向循环链表初始化
struct doublelist *list_init()
{
	struct doublelist *head=malloc(sizeof(struct doublelist));
	head->next=NULL;
	head->prev=NULL;
	return head;
}

//双向链表尾插
int list_insert_tail(struct doublelist *head,char *newname,float newprice,int newnum,char *picpath)
{
	//准备新节点
	struct doublelist *newnode=malloc(sizeof(struct doublelist));
	
	strcpy(newnode->name,newname);
	newnode->price=newprice;
	newnode->num=newnum;
	strcpy(newnode->picpath,picpath);
	
	newnode->next=NULL;
	newnode->prev=NULL;
	
	//找到尾部
	struct doublelist *p=head;
	while(p->next!=NULL)
		p=p->next;
	
	//循环结束，p到了末尾
	newnode->prev=p;
	p->next=newnode;
	return 0;
}


//双向链表删除节点
int list_del(struct doublelist *head,char *delname)
{
	//找到要删除的节点
	struct doublelist *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		if(strcmp(p->name,delname)==0)
			break;
	}
	
	//判断要删除节点是不是最后一个节点
	if(p->next==NULL)
	{
		p->prev->next=NULL;
		p->prev=NULL;
		free(p);
	}
	else
	{
		//删除p这个节点
		p->prev->next=p->next;
		p->next->prev=p->prev;
		free(p);
	}
	
	return 0;
}

//双向链表修改节点数据
int list_update(struct doublelist *head,char *oldname,char *newname,float newprice,int newnum,char *newpath)
{
	struct doublelist *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		if(strcmp(p->name,oldname)==0)
		{
			strcpy(p->name,newname);
			p->price=newprice;
			p->num=newnum;
			strcpy(p->picpath,newpath);
			break;
		}
			
			
			
	}
	return 0;
}


//双向循环链表遍历打印
int list_show(struct doublelist *head)
{
	int t=0;//记录链表除去头节点长度
	struct doublelist *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		t++;
		printf("%s %.1f %d %s\n",p->name,p->price,p->num,p->picpath);
	}	
	return t;
}



